# coding=utf-8
#


"""
根据用户名密码登录到管理员后台
"""

import json

from iminer.sm_log import getLogger

from iminer.user.models import User

from iminer.account.models import Account

from iminer.utils.http import make_api_response
from iminer.utils.errorcode import ErrorResponse

from iminer.serializers import format_model_response

from django.contrib.auth import login as django_login
from django.contrib.auth import logout as django_logout

from iminer.utils.decorator import check_user


logger = getLogger("iminer.user.views")


def login(request, *args, **kwargs):
    """ 使用手机验证码登录 """

    data = json.loads(request.body)

    username = data.get("username", "")
    password = data.get("password", "")

    user = User.objects.filter(name=username).first()
    if not user:
        return ErrorResponse.get(ErrorResponse.NO_SUCH_USER)

    if not user.check_password(password):
        return ErrorResponse.get(ErrorResponse.WRONG_PASSWORD)

    # 密码验证通过，登录
    return make_api_response(format_model_response(user))


@check_user
def me(request, *args, **kwargs):
    """ """
    logger.info("Got userinfo :%s" % request.user.id)

    user = request.user
    accounts = Account.objects.filter(user=user)
    user.account = format_model_response(accounts)
    return make_api_response(format_model_response(user))


@check_user
def logout(request, *args, **kwargs):
    """ 退出登录 """

    django_logout(request)
    # 密码验证通过，登录
    return make_api_response(format_model_response({}))
